/**
 * 问题
 * @todo 移动端自定义按钮交互css,难道必须要监听tap事件？
 * @done 选取本地图片并展示 https://www.cnblogs.com/wxxwjef/p/10495149.html
 * @todo 只完成了pc端的图片选择，没有尝试移动端的图片选择
 * @done 页面跳转
 * 
 * 待思考
 * @todo 设置image元素的src后，为啥立即拿不到 改元素的宽度。就是要等渲染吗？
 */
let imgData = null;
let imgSize = {
    width: 0,
    height: 0,
    origin_width: 0,
    origin_height: 0,
};
let scale = 1;

function emitClickEvent() {
    let ipt = document.getElementById("select_img_ipt");
    ipt.click();
}

function backHandler() {
    document.getElementById('mask').style.display = "none";
}

function sureHandler() {
    console.log(imgData, imgSize, scale);
    localStorage.setItem("sc_img_data", JSON.stringify({ img: imgData, size: imgSize, scale }));


    window.location.href = "../draw_rect/index.html";
}

/**
 * 
 * @function 
 * @description 拿选区的截图数据
 * @link 选择本地图片 https://www.cnblogs.com/wxxwjef/p/10495149.html
 * @param {*} file 
 * @returns 
 */
function selectImage(file) {
    // console.log(a);
    if (!file.files || !file.files[0]) {
        return;
    }
    var reader = new FileReader();
    reader.onload = function (evt) {
        imgData = evt.target.result;
        document.getElementById('mask').style.display = "block";
        document.getElementById('image_show').src = imgData;
        // console.log(imgData);
        setTimeout(() => {
            // console.log(imgData,imgData.width, imgData.height);
            adjustImage();
        }, 50);
    }
    reader.readAsDataURL(file.files[0]);
}

/**
 * 
 * @function 
 * @description 自适应图片，按道理来说，截图应该正好铺满整个页面的，但为了防止意外
 * @param {*} file 
 * @returns 
 */

function adjustImage() {
    let dom = document.getElementById('image_show');
    let sc_w = document.body.clientWidth;
    let sc_h = document.body.clientHeight;

    let origin_width = dom.width;
    let origin_height = dom.height;

    if ((origin_height / origin_width) > (sc_h / sc_w)) {
        // 按高度适配
        h = sc_h;// origin_height * scale = sc_h => scale = sc_h/  origin_height
        scale = sc_h / origin_height;
        w = parseFloat((origin_width * scale).toFixed(3));
    } else {
        // 按宽度适配
        w = sc_w;
        scale = sc_w / origin_width;
        h = parseFloat((origin_height * scale).toFixed(3));
    }

    dom.style.width = w + "px";
    dom.style.height = h + "px";

    imgSize.width = w;
    imgSize.height = h;

    imgSize.origin_width = origin_width;
    imgSize.origin_height = origin_height;
    // console.log(origin_width, origin_height, w, h, sc_w, sc_h);
}